package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信发送模块")
@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送短信")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok().message("短信已经发送，有效时间为5分钟");
        }
        //生成随机值传递给阿里云
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用service中短信发送的方法
        //设置有效时间
        boolean isSend = msmService.send(param, phone);
        if (isSend) {
            //发送成功，把发送成功的验证码放到redis里面
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败！");
        }

    }

    @ApiOperation(value = "发送邮箱验证码")
    @GetMapping("sendMail/{mail}")
    public R sendMail(@PathVariable("mail") String mail) {
        //从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(mail);
        if (!StringUtils.isEmpty(code)) {
            return R.ok().message("邮箱验证码已经发送，有效时间为5分钟");
        }
        //生成随机值传递给邮箱
        code = RandomUtil.getFourBitRandom();
        //调用service中短信发送的方法
        //设置有效时间
        boolean isSend = msmService.sendMail(code, mail);
        if (isSend) {
            //发送成功，把发送成功的验证码放到redis里面
            redisTemplate.opsForValue().set(mail, code, 2, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("邮箱验证码发送失败！");
        }
    }


}
